<!DOCTYPE html>
<html class="x-admin-sm" style="overflow-y: hidden">
<head>
    <th:block th:insert="head/head :: common_head"></th:block>
    <link rel="stylesheet" th:href="@{/ztree/css/metroStyle/metroStyle.css}">
    <script type="text/javascript" th:src="@{/jsfiles/xm-select.js?t=20813}" charset="utf-8"></script>

    <!-- 高德地图安全密钥配置 -->
    <script>
        window._AMapSecurityConfig = {
            securityJsCode: '7a0a36e28a5c103529a98091864e6c53',
        };
    </script>

    <style>
        /* 保持原有样式不变 */
        :root {
            --bg-color: #f8f9fa;
            --text-color: #333;
            --panel-bg: #fff;
            --highlight-blue: #0066CC;
            --highlight-red: #FF3333;
            --highlight-yellow: #FF9933;
            --border-color: #e5e6eb;
        }
        body {
            background-color: var(--bg-color);
            margin: 0;
            padding: 10px;
        }
        .left-panel {
            background: var(--panel-bg);
            height: calc(100vh - 40px);
            border-radius: 8px;
            padding: 20px;
            color: var(--text-color);
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            overflow-y: auto;
            box-sizing: border-box;
        }
        .panel-title {
            font-size: 16px;
            font-weight: bold;
            color: var(--highlight-blue);
            margin-bottom: 15px;
            padding-bottom: 5px;
            border-bottom: 1px solid #e6e6e6;
        }
        .address-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            width: 100%;
        }
        .address-input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            outline: none;
            font-size: 14px;
            box-sizing: border-box;
        }
        .address-input:focus {
            border-color: var(--highlight-blue);
        }
        .scene-group {
            margin-bottom: 20px;
        }
        .scene-options {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .scene-tag {
            padding: 6px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .scene-tag.active {
            background-color: var(--highlight-blue);
            color: white;
            border-color: var(--highlight-blue);
        }
        .filter-panel {
            border: 1px dashed #ccc;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .filter-group {
            margin-bottom: 15px;
        }
        .filter-item-label {
            display: block;
            margin-bottom: 8px;
            font-size: 13px;
            color: var(--text-color);
        }
        .filter-options {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        .filter-option {
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 13px;
        }
        .map-panel {
            height: calc(100vh - 40px);
            border-radius: 8px;
            overflow: hidden;
            position: relative;
            box-sizing: border-box;
        }
        #mapContainer {
            width: 100%;
            height: 100%;
        }
        .right-panel {
            background: var(--panel-bg);
            height: calc(100vh - 40px);
            border-radius: 8px;
            padding: 20px;
            color: var(--text-color);
            overflow-y: auto;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            box-sizing: border-box;
        }
        .recommend-list {
            margin-bottom: 20px;
        }
        .potential-item {
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: background-color 0.2s;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .potential-item:hover {
            background-color: #f5f7fa;
        }
        .potential-info {
            flex: 1;
        }
        .potential-title {
            font-weight: 500;
            color: var(--highlight-blue);
            margin-bottom: 4px;
        }
        .potential-meta {
            font-size: 11px;
            color: #999;
        }
        .collect-btn {
            background: none;
            border: none;
            color: #ccc;
            cursor: pointer;
            font-size: 16px;
        }
        .collect-btn.collected {
            color: var(--highlight-red);
        }
        .detail-panel {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            padding: 18px;
            border: 1px solid #f0f0f0;
            margin-bottom: 20px;
            display: none;
        }
        .detail-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        .detail-title {
            font-size: 15px;
            font-weight: 600;
            color: var(--highlight-blue);
        }
        .detail-collect-btn {
            padding: 4px 10px;
            border: 1px solid var(--highlight-red);
            color: var(--highlight-red);
            border-radius: 4px;
            background: none;
            cursor: pointer;
            font-size: 13px;
        }
        .detail-collect-btn.collected {
            background-color: var(--highlight-red);
            color: white;
        }
        .detail-item {
            margin-bottom: 12px;
        }
        .detail-label {
            font-size: 13px;
            font-weight: 600;
            color: #666;
            margin-bottom: 4px;
        }
        .detail-value {
            font-size: 12px;
            color: #555;
        }
        .surround-panel {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            padding: 18px;
            border: 1px solid #f0f0f0;
            margin-bottom: 20px;
        }
        .surround-list {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 10px;
        }
        .surround-tag {
            padding: 4px 10px;
            background-color: #f0f2f5;
            border-radius: 12px;
            font-size: 12px;
            color: #666;
        }
        .collect-list-panel {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            padding: 18px;
            border: 1px solid #f0f0f0;
            margin-bottom: 20px;
        }
        .collect-item {
            padding: 10px 0;
            border-bottom: 1px solid #f5f5f5;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .collect-info {
            flex: 1;
        }
        .collect-name {
            font-size: 13px;
            color: var(--highlight-blue);
        }
        .collect-coord {
            font-size: 11px;
            color: #999;
        }
        .cancel-collect-btn {
            background: none;
            border: none;
            color: #ccc;
            cursor: pointer;
            font-size: 14px;
        }
        .cancel-collect-btn:hover {
            color: var(--highlight-red);
        }
        .map-loading {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(0,0,0,0.5);
            color: white;
            z-index: 100;
            font-size: 18px;
        }
        .search-status {
            position: absolute;
            top: 20px;
            right: 20px;
            background: rgba(255,255,255,0.9);
            padding: 10px 15px;
            border-radius: 4px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            z-index: 90;
            display: none;
        }
        .layui-btn-theme {
            background-color: var(--highlight-blue);
            border-color: var(--highlight-blue);
            color: white;
            padding: 8px 18px;
            border-radius: 4px;
            cursor: pointer;
            border: none;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        .layui-btn-theme:hover {
            background-color: #0052a3;
        }
        .no-selection {
            display: flex;
            height: 100%;
            align-items: center;
            justify-content: center;
            color: #999;
            flex-direction: column;
            text-align: center;
            padding: 20px;
        }
        .no-selection i {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.5;
        }
        .layui-col-space15 {
            margin: 0 -7.5px;
        }
        .layui-col-space15 > [class*="layui-col-"] {
            padding: 0 7.5px;
        }
        /* 标记说明样式 */
        .marker-desc-panel {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            padding: 18px;
            border: 1px solid #f0f0f0;
        }
        .marker-desc-list {
            margin-top: 10px;
            columns: 1; /* 单列显示，清晰直观 */
        }
        .marker-desc-item {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
            font-size: 12px;
            break-inside: avoid; /* 防止跨列断开 */
        }
        .marker-desc-icon {
            width: 24px;
            height: 24px;
            object-fit: contain;
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 2px;
        }
        .marker-desc-text {
            color: #666;
            flex: 1;
        }
    </style>
</head>
<body>
<!-- 外层容器 -->
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <!-- 左侧：3列 - 选址设置+筛选条件 -->
        <div class="layui-col-md3">
            <div class="left-panel">
                <div class="panel-title">选址设置</div>
                <div class="address-group">
                    <input type="text" class="address-input" id="addressInput" placeholder="输入中心地址（如：武汉市武昌区）" value="武汉市武昌区">
                    <button class="layui-btn-theme" onclick="setCenterPoint()">确定区域</button>
                </div>
                <div class="scene-group">
                    <div class="filter-item-label">选址场景：</div>
                    <div class="scene-options">
                        <div class="scene-tag active" data-scene="post网点">邮政网点</div>
                        <div class="scene-tag" data-scene="theme邮局">主题邮局</div>
                    </div>
                </div>
                <div class="filter-panel" id="filterPanel"></div>
                <button class="layui-btn-theme" style="width: 100%;" onclick="recommendPotentialPoints()">推荐潜在选址</button>
            </div>
        </div>

        <!-- 中间：6列 - 高德地图 -->
        <div class="layui-col-md6">
            <div class="map-panel">
                <div class="map-loading">
                    <i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i>
                    地图加载中...
                </div>
                <div class="search-status" id="searchStatus">
                    <i class="layui-icon layui-icon-loading"></i> 正在分析潜在选址...
                </div>
                <div id="mapContainer"></div>
            </div>
        </div>

        <!-- 右侧：3列 - 推荐列表+详情+收藏+标记说明 -->
        <div class="layui-col-md3">
            <div class="right-panel">
                <div class="recommend-list" id="recommendList">
                    <div class="panel-title">潜在选址推荐 (0)</div>
                    <div class="no-selection">
                        <i class="layui-icon layui-icon-map"></i>
                        <p>请先确定区域并推荐潜在选址</p>
                    </div>
                </div>
                <div class="detail-panel" id="detailPanel">
                    <div class="detail-header">
                        <div class="detail-title">选址详情</div>
                        <button class="detail-collect-btn" id="detailCollectBtn" onclick="collectPotentialPoint()">收藏</button>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">坐标信息</div>
                        <div class="detail-value" id="detailCoord">114.30, 30.60</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">符合条件</div>
                        <div class="detail-value" id="detailFitConditions">500米无竞品、近公交站、社区型商圈</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">推荐理由</div>
                        <div class="detail-value" id="detailReason">该区域为成熟社区，覆盖人口1200户，交通便利，无同类竞品</div>
                    </div>
                </div>
                <div class="surround-panel" id="surroundPanel">
                    <div class="panel-title">周边配套（按类型区分）</div>
                    <div class="surround-list" id="surroundList">
                        <span class="surround-tag">公交站（150米）</span>
                        <span class="surround-tag">居民区（50米）</span>
                    </div>
                </div>
                <div class="collect-list-panel">
                    <div class="panel-title">我的收藏</div>
                    <div id="collectList">
                        <div style="text-align: center; color: #999; padding: 10px 0; font-size: 12px;">暂无收藏的选址</div>
                    </div>
                </div>
                <!-- 新增标记说明区域（含所有细分类型） -->
                <div class="marker-desc-panel" style="margin-top: 20px;">
                    <div class="panel-title">标记说明（按类型区分）</div>
                    <div class="marker-desc-list">
                        <!-- 核心选址类 -->
                        <div class="marker-desc-item">
                            <img src="/zhdt/image/zhdt/bjdz.png" class="marker-desc-icon" alt="潜在选址">
                            <span class="marker-desc-text">潜在选址</span>
                        </div>
                        <!-- 交通类 -->
                        <div class="marker-desc-item">
                            <img src="/zhdt/image/zhdt/bus.png" class="marker-desc-icon" alt="公交站">
                            <span class="marker-desc-text">公交站</span>
                        </div>
                        <div class="marker-desc-item">
                            <img src="/zhdt/image/zhdt/metro.png" class="marker-desc-icon" alt="地铁站">
                            <span class="marker-desc-text">地铁站</span>
                        </div>
                        <div class="marker-desc-item">
                            <img src="/zhdt/image/zhdt/parking.png" class="marker-desc-icon" alt="停车场">
                            <span class="marker-desc-text">停车场</span>
                        </div>
                        <!-- 生活配套类 -->
                        <div class="marker-desc-item">
                            <img src="/zhdt/image/zhdt/supermarket.png" class="marker-desc-icon" alt="超市">
                            <span class="marker-desc-text">超市</span>
                        </div>
                        <div class="marker-desc-item">
                            <img src="/zhdt/image/zhdt/restaurant.png" class="marker-desc-icon" alt="餐饮">
                            <span class="marker-desc-text">餐饮设施</span>
                        </div>
                        <!-- 教育类 -->
                        <div class="marker-desc-item">
                            <img src="/zhdt/image/zhdt/school.png" class="marker-desc-icon" alt="学校（小学/幼儿园）">
                            <span class="marker-desc-text">学校（小学/幼儿园）</span>
                        </div>
                        <!-- 商圈/居住类 -->
                        <div class="marker-desc-item">
                            <img src="/zhdt/image/zhdt/business.png" class="marker-desc-icon" alt="商圈">
                            <span class="marker-desc-text">商圈（购物中心/商业街）</span>
                        </div>
                        <div class="marker-desc-item">
                            <img src="/zhdt/image/zhdt/community.png" class="marker-desc-icon" alt="住宅小区">
                            <span class="marker-desc-text">住宅小区</span>
                        </div>
                        <!-- 预留扩展类 -->
                        <div class="marker-desc-item">
                            <img src="/zhdt/image/zhdt/js.png" class="marker-desc-icon" alt="预留标记" style="opacity: 0.6;">
                            <span class="marker-desc-text">预留扩展标记（待补充）</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 全局变量
    var map;
    var mapLoaded = false;
    var placeSearch;
    var currentCenter = null;
    var currentScene = "post网点";
    var currentRadius = 2000;
    var potentialPoints = [];
    var collectedPoints = JSON.parse(localStorage.getItem('collectedPotentialPoints')) || [];
    var selectedPoint = null;
    var potentialMarkers = [];
    var surroundMarkers = [];

    // 【核心配置】周边配套类型-图标映射表（模拟路径，你后续替换实际图片）
    const surroundIconMap = {
        公交站: '/zhdt/image/zhdt/bus.png',
        地铁站: '/zhdt/image/zhdt/metro.png',
        超市: '/zhdt/image/zhdt/supermarket.png',
        学校: '/zhdt/image/zhdt/school.png',
        商圈: '/zhdt/image/zhdt/business.png',
        餐饮: '/zhdt/image/zhdt/restaurant.png',
        停车场: '/zhdt/image/zhdt/parking.png',
        住宅小区: '/zhdt/image/zhdt/community.png'
    };

    // 筛选条件配置
    const filterConfigs = {
        "post网点": [
            { id: "competition", name: "周边竞争", options: [
                    { value: "no500", label: "500米内无其他邮政网点" },
                    { value: "no1000", label: "1000米内无其他邮政网点" },
                    { value: "ignore", label: "不限制" }
                ]},
            { id: "population", name: "覆盖人口", options: [
                    { value: "500+", label: "1公里内居民≥500户" },
                    { value: "1000+", label: "1公里内居民≥1000户" },
                    { value: "2000+", label: "1公里内居民≥2000户" }
                ]},
            { id: "traffic", name: "交通便利度", options: [
                    { value: "metro300", label: "距地铁站≤300米" },
                    { value: "bus200", label: "距公交站≤200米" },
                    { value: "parking", label: "附近有停车场" }
                ]},
            { id: "businessArea", name: "商圈类型", options: [
                    { value: "community", label: "社区型" },
                    { value: "commercial", label: "商业区" },
                    { value: "industrial", label: "工业区" }
                ]}
        ],
        "theme邮局": [
            { id: "scenicType", name: "景点类型", options: [
                    { value: "historical", label: "历史文化景点" },
                    { value: "natural", label: "自然景区" },
                    { value: "internet", label: "网红打卡点" },
                    { value: "cultural", label: "文化艺术区" }
                ]},
            { id: "visitorFlow", name: "游客流量", options: [
                    { value: "1000+", label: "日均游客≥1000人" },
                    { value: "3000+", label: "日均游客≥3000人" },
                    { value: "5000+", label: "日均游客≥5000人" }
                ]},
            { id: "facility", name: "周边配套", options: [
                    { value: "parking", label: "距停车场≤200米" },
                    { value: "toilet", label: "距卫生间≤100米" },
                    { value: "restaurant", label: "周边有餐饮设施" }
                ]},
            { id: "themeCompetition", name: "周边竞品", options: [
                    { value: "no1000", label: "1公里内无其他主题邮局" },
                    { value: "no3000", label: "3公里内无其他主题邮局" },
                    { value: "ignore", label: "不限制" }
                ]}
        ]
    };

    // 初始化（移除layui依赖，直接执行）
    function init() {
        loadAmapApi(); // 异步加载高德API
        bindSceneEvents();
        loadFilterConditions(currentScene);
        renderCollectList();
    }

    // 页面加载完成后初始化
    window.onload = init;

    // 异步加载高德地图API
    function loadAmapApi() {
        const script = document.createElement('script');
        script.src = 'https://webapi.amap.com/maps?v=2.0&key=6f2409fb651e7a7831482d0df918e001';
        script.onload = initMap;
        script.onerror = () => {
            alert('地图加载失败，请刷新重试');
            document.querySelector('.map-loading').style.display = 'none';
        };
        document.head.appendChild(script);
    }

    // 初始化地图
    function initMap() {
        if (typeof AMap === 'undefined') return;
        try {
            map = new AMap.Map('mapContainer', {
                center: [114.30, 30.60],
                zoom: 12,
                viewMode: '2D'
            });
            map.on('complete', () => {
                mapLoaded = true;
                document.querySelector('.map-loading').style.display = 'none';
            });
        } catch (e) {
            console.error('地图初始化失败:', e);
            alert('地图初始化失败: ' + e.message);
            document.querySelector('.map-loading').style.display = 'none';
        }
    }

    // 绑定场景切换事件
    function bindSceneEvents() {
        document.querySelectorAll('.scene-tag').forEach(tag => {
            tag.addEventListener('click', function() {
                document.querySelectorAll('.scene-tag').forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                currentScene = this.getAttribute('data-scene');
                loadFilterConditions(currentScene);
            });
        });
    }

    // 加载筛选条件
    function loadFilterConditions(scene) {
        const filterPanel = document.getElementById('filterPanel');
        const configs = filterConfigs[scene];
        let html = `<div class="filter-item-label">${scene === 'post网点' ? '邮政网点筛选条件' : '主题邮局筛选条件'}</div>`;
        configs.forEach(group => {
            html += `
                <div class="filter-group">
                    <div class="filter-item-label">${group.name}</div>
                    <div class="filter-options">
                        ${group.options.map(option => `
                            <label class="filter-option">
                                <input type="checkbox" name="${group.id}" value="${option.value}">
                                ${option.label}
                            </label>
                        `).join('')}
                    </div>
                </div>
            `;
        });
        filterPanel.innerHTML = html;
    }

    // 设置中心地址
    function setCenterPoint() {
        const address = document.getElementById('addressInput').value.trim();
        if (!address) { alert("请输入地址"); return; }

        document.querySelector('.map-loading').style.display = 'flex';
        document.querySelector('.map-loading').innerHTML = '<i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i> 解析地址中...';

        AMap.plugin('AMap.Geocoder', () => {
            const geocoder = new AMap.Geocoder();
            geocoder.getLocation(address, (status, result) => {
                if (status === 'complete' && result.geocodes.length > 0) {
                    const geocode = result.geocodes[0];
                    currentCenter = [geocode.location.lng, geocode.location.lat];
                    map.setCenter(currentCenter);
                    map.setZoom(15);
                    AMap.plugin('AMap.Circle', drawSearchCircle);
                } else {
                    alert("地址解析失败");
                }
                document.querySelector('.map-loading').style.display = 'none';
            });
        });
    }

    // 绘制搜索范围圆
    function drawSearchCircle() {
        const circles = map.getAllOverlays('circle');
        circles.forEach(circle => map.remove(circle));
        const circle = new AMap.Circle({
            center: currentCenter,
            radius: currentRadius,
            strokeColor: "#0066CC",
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: "#0066CC",
            fillOpacity: 0.1
        });
        map.add(circle);
    }

    // 推荐潜在选址
    function recommendPotentialPoints() {
        if (!mapLoaded || !currentCenter) {
            alert("请先确认地图加载完成并设置中心地址");
            return;
        }

        const selectedFilters = getSelectedFilters();
        document.getElementById('searchStatus').style.display = 'block';
        clearPotentialMarkers();
        clearSurroundMarkers(); // 搜索新选址时清除旧周边标记

        // 生成3个候选点（围绕中心点偏移）
        const candidates = [];
        for (let i = 0; i < 3; i++) {
            const offsetLng = (Math.random() - 0.5) * 0.015;
            const offsetLat = (Math.random() - 0.5) * 0.01;
            const lng = (currentCenter[0] + offsetLng).toFixed(6);
            const lat = (currentCenter[1] + offsetLat).toFixed(6);
            candidates.push({ lng, lat, id: `point_${Date.now()}_${i}` });
        }

        // 批量验证候选点是否符合筛选条件
        Promise.all(candidates.map(candidate => verifyCandidate(candidate, selectedFilters)))
            .then(validPoints => {
                potentialPoints = validPoints.filter(p => p.isValid);
                renderRecommendList();
                markPotentialPoints();
                document.getElementById('searchStatus').style.display = 'none';
            });
    }

    // 验证候选点是否符合筛选条件
    function verifyCandidate(candidate, filters) {
        return new Promise(resolve => {
            const point = { ...candidate, fitConditions: [], reason: '', isValid: false };
            const tasks = [];

            // 1. 检查周边竞品
            if (currentScene === 'post网点' && filters.competition) {
                const distance = filters.competition.includes('no500') ? 500 : 1000;
                tasks.push(checkCompetitors(point.lng, point.lat, '邮政网点', distance));
            }

            // 2. 检查交通便利度
            if (filters.traffic && filters.traffic.includes('bus200')) {
                tasks.push(checkFacility(point.lng, point.lat, '公交站', 200));
            }
            if (filters.traffic && filters.traffic.includes('metro300')) {
                tasks.push(checkFacility(point.lng, point.lat, '地铁站', 300));
            }

            // 3. 检查人口覆盖
            if (filters.population) {
                tasks.push(estimatePopulation(point.lng, point.lat, filters.population));
            }

            // 4. 检查商圈类型
            tasks.push(judgeBusinessArea(point.lng, point.lat));

            // 执行所有验证任务
            Promise.all(tasks).then(results => {
                results.forEach(res => {
                    if (res.passed) point.fitConditions.push(res.label);
                });

                point.isValid = point.fitConditions.length >= 2;

                if (point.isValid) {
                    point.reason = generateRealReason(point.fitConditions, results);
                }

                resolve(point);
            });
        });
    }

    // 检查周边竞品
    function checkCompetitors(lng, lat, keyword, distance) {
        return new Promise(resolve => {
            AMap.plugin('AMap.PlaceSearch', () => {
                const search = new AMap.PlaceSearch({ pageSize: 1 });
                search.searchNearBy(keyword, [lng, lat], distance, (status, result) => {
                    const hasCompetitor = status === 'complete' && result.poiList.pois.length > 0;
                    resolve({
                        passed: !hasCompetitor,
                        label: `${distance}米内无${keyword}`
                    });
                });
            });
        });
    }

    // 检查周边设施
    function checkFacility(lng, lat, facility, distance) {
        return new Promise(resolve => {
            AMap.plugin('AMap.PlaceSearch', () => {
                const search = new AMap.PlaceSearch({ pageSize: 1 });
                search.searchNearBy(facility, [lng, lat], distance, (status, result) => {
                    const hasFacility = status === 'complete' && result.poiList.pois.length > 0;
                    resolve({
                        passed: hasFacility,
                        label: `近${facility}（${hasFacility ? result.poiList.pois[0].distance + '米' : '未达标'}）`
                    });
                });
            });
        });
    }

    // 估算人口覆盖
    function estimatePopulation(lng, lat, populationFilter) {
        return new Promise(resolve => {
            AMap.plugin('AMap.PlaceSearch', () => {
                const search = new AMap.PlaceSearch({ pageSize: 20 });
                search.searchNearBy('小区', [lng, lat], 1000, (status, result) => {
                    if (status !== 'complete') {
                        resolve({ passed: false, label: '人口数据获取失败' });
                        return;
                    }

                    const communityCount = result.poiList.pois.length;
                    const estimatedHouseholds = communityCount * 200;
                    let passed = false;
                    let label = `1公里内约${estimatedHouseholds}户`;

                    if (populationFilter.includes('500+') && estimatedHouseholds >= 500) passed = true;
                    if (populationFilter.includes('1000+') && estimatedHouseholds >= 1000) passed = true;
                    if (populationFilter.includes('2000+') && estimatedHouseholds >= 2000) passed = true;

                    resolve({ passed, label });
                });
            });
        });
    }

    // 判断商圈类型
    function judgeBusinessArea(lng, lat) {
        return new Promise(resolve => {
            AMap.plugin('AMap.PlaceSearch', () => {
                const search = new AMap.PlaceSearch({ pageSize: 30 });
                search.searchNearBy('', [lng, lat], 500, (status, result) => {
                    if (status !== 'complete') {
                        resolve({ passed: false, label: '商圈类型无法判断' });
                        return;
                    }

                    const types = { community: 0, commercial: 0, industrial: 0 };
                    result.poiList.pois.forEach(poi => {
                        if (poi.type.includes('住宅') || poi.type.includes('小区')) types.community++;
                        if (poi.type.includes('购物') || poi.type.includes('餐饮')) types.commercial++;
                        if (poi.type.includes('工业') || poi.type.includes('厂房')) types.industrial++;
                    });

                    const mainType = Object.keys(types).sort((a, b) => types[b] - types[a])[0];
                    const typeMap = {
                        community: '社区型商圈',
                        commercial: '商业区',
                        industrial: '工业区'
                    };

                    resolve({ passed: true, label: typeMap[mainType] });
                });
            });
        });
    }

    // 生成推荐理由
    function generateRealReason(conditions, results) {
        const population = results.find(r => r.label.includes('1公里内约'))?.label || '未知';
        const traffic = results.find(r => r.label.includes('近公交站') || r.label.includes('近地铁站'))?.label || '交通一般';
        const businessArea = results.find(r => r.label.includes('商圈'))?.label || '普通区域';
        const competition = conditions.find(c => c.includes('无竞品')) ? '无同类竞品' : '周边有竞品';

        return `该区域为${businessArea}，${population}，${traffic}，${competition}，适合新建邮政网点开展业务。`;
    }

    // 渲染推荐列表
    function renderRecommendList() {
        const recommendList = document.getElementById('recommendList');
        const panelTitle = recommendList.querySelector('.panel-title');
        panelTitle.innerText = `潜在选址推荐 (${potentialPoints.length})`;

        if (potentialPoints.length === 0) {
            recommendList.innerHTML = `
                <div class="panel-title">潜在选址推荐 (0)</div>
                <div class="no-selection">
                    <i class="layui-icon layui-icon-search"></i>
                    <p>未找到符合条件的潜在选址</p>
                </div>
            `;
            return;
        }

        let html = `<div class="panel-title">潜在选址推荐 (${potentialPoints.length})</div>`;
        potentialPoints.forEach(point => {
            html += `
                <div class="potential-item" onclick="selectPotentialPoint('${point.id}')">
                    <div class="potential-info">
                        <div class="potential-title">选址${potentialPoints.findIndex(p => p.id === point.id) + 1}</div>
                        <div class="potential-meta">${point.lng}, ${point.lat}</div>
                        <div class="potential-meta">${point.fitConditions.slice(0, 2).join('、')}</div>
                    </div>
                    <button class="collect-btn ${point.collected ? 'collected' : ''}" onclick="event.stopPropagation(); collectPotentialPoint('${point.id}')">
                        <i class="layui-icon">${point.collected ? '&#xe609;' : '&#xe640;'}</i>
                    </button>
                </div>
            `;
        });
        recommendList.innerHTML = html;
    }

    // 标记潜在选址（使用本地图标）
    function markPotentialPoints() {
        clearPotentialMarkers();
        const potentialIcon = new AMap.Icon({
            size: new AMap.Size(30, 30),
            image: '/zhdt/image/zhdt/bjdz.png',
            imageSize: new AMap.Size(30, 30),
            anchor: 'bottom-center',
            imageOffset: new AMap.Pixel(0, 0) // 确保图标显示完整
        });

        potentialPoints.forEach(point => {
            const marker = new AMap.Marker({
                position: [point.lng, point.lat],
                title: `潜在选址${potentialPoints.findIndex(p => p.id === point.id) + 1}`,
                icon: potentialIcon,
                zIndex: 50 // 潜在选址标记层级最高，不被覆盖
            });
            marker.setMap(map);
            potentialMarkers.push(marker);
            marker.on('click', () => selectPotentialPoint(point.id));
        });
    }

    // 选择潜在选址
    function selectPotentialPoint(pointId) {
        selectedPoint = potentialPoints.find(p => p.id === pointId);
        if (!selectedPoint) return;

        // 显示详情面板
        document.getElementById('detailPanel').style.display = 'block';
        document.getElementById('surroundPanel').style.display = 'block';
        document.getElementById('detailCoord').innerText = `${selectedPoint.lng}, ${selectedPoint.lat}`;
        document.getElementById('detailFitConditions').innerText = selectedPoint.fitConditions.join('、');
        document.getElementById('detailReason').innerText = selectedPoint.reason;

        // 更新收藏按钮状态
        const detailCollectBtn = document.getElementById('detailCollectBtn');
        if (selectedPoint.collected) {
            detailCollectBtn.classList.add('collected');
            detailCollectBtn.innerHTML = '已收藏';
        } else {
            detailCollectBtn.classList.remove('collected');
            detailCollectBtn.innerHTML = '收藏';
        }

        // 定位到选中的选址
        map.setCenter([selectedPoint.lng, selectedPoint.lat]);
        map.setZoom(16);

        // 加载该选址的周边配套（核心：按类型区分图标）
        loadSurroundFacilities(selectedPoint.lng, selectedPoint.lat);
    }

    // 加载周边配套（核心修复：按类型使用不同图标）
    function loadSurroundFacilities(lng, lat) {
        clearSurroundMarkers(); // 清除原有周边标记

        // 先通过逆地理编码获取城市，提高搜索准确性
        AMap.plugin('AMap.Geocoder', () => {
            const geocoder = new AMap.Geocoder({ radius: 1000 });
            geocoder.getAddress([lng, lat], (status, result) => {
                const city = status === 'complete' ? result.regeocode.addressComponent.city : '武汉市';

                AMap.plugin('AMap.PlaceSearch', () => {
                    // 配置搜索参数，增加city提高准确性
                    placeSearch = new AMap.PlaceSearch({
                        pageSize: 2, // 每个类型返回2个结果
                        city: city,
                        radius: 1000 // 扩大搜索范围到1000米，覆盖更多配套
                    });

                    // 【详细周边类型】拆分细化，对应独立图标
                    const surroundTypes = [
                        { name: '公交站', keyword: '公交站点', iconKey: '公交站' },
                        { name: '地铁站', keyword: '地铁站点', iconKey: '地铁站' },
                        { name: '超市', keyword: '超市', iconKey: '超市' },
                        { name: '学校', keyword: '小学|幼儿园', iconKey: '学校' },
                        { name: '商圈', keyword: '购物中心|商业街', iconKey: '商圈' },
                        { name: '餐饮', keyword: '餐饮服务', iconKey: '餐饮' },
                        { name: '停车场', keyword: '停车场', iconKey: '停车场' },
                        { name: '住宅小区', keyword: '住宅小区', iconKey: '住宅小区' }
                    ];

                    const surroundList = document.getElementById('surroundList');
                    surroundList.innerHTML = '';
                    let loaded = 0;

                    surroundTypes.forEach(type => {
                        placeSearch.searchNearBy(type.keyword, [lng, lat], 1000, (status, result) => {
                            loaded++;
                            if (status === 'complete' && result.poiList.pois.length > 0) {
                                // 取每个类型最近的1个结果
                                const poi = result.poiList.pois[0];

                                // 添加周边配套文字标签
                                const tag = document.createElement('span');
                                tag.className = 'surround-tag';
                                tag.innerText = `${type.name}（${poi.distance}米）`;
                                surroundList.appendChild(tag);

                                // 获取该类型对应的图标路径（从映射表中取）
                                const iconPath = surroundIconMap[type.iconKey];

                                // 配置该类型的独立图标
                                const icon = new AMap.Icon({
                                    size: new AMap.Size(24, 24),
                                    image: iconPath,
                                    imageSize: new AMap.Size(24, 24),
                                    anchor: 'bottom-center',
                                    imageOffset: new AMap.Pixel(0, 0)
                                });

                                // 创建并添加周边标记
                                const marker = new AMap.Marker({
                                    position: [poi.location.lng, poi.location.lat],
                                    title: `${type.name}（${poi.distance}米）`,
                                    icon: icon,
                                    zIndex: 20 // 层级低于潜在选址
                                });
                                marker.setMap(map);
                                surroundMarkers.push(marker);
                            }

                            // 所有类型搜索完成后，若仍无配套则显示提示
                            if (loaded === surroundTypes.length && surroundList.children.length === 0) {
                                surroundList.innerHTML = '<span class="surround-tag">1000米内无配套设施</span>';
                            }
                        });
                    });
                });
            });
        });
    }

    // 收藏功能
    function collectPotentialPoint(pointId) {
        const targetId = pointId || (selectedPoint ? selectedPoint.id : null);
        if (!targetId) return;

        const targetPoint = potentialPoints.find(p => p.id === targetId);
        if (!targetPoint) return;

        targetPoint.collected = !targetPoint.collected;
        if (targetPoint.collected) {
            saveToDatabase(targetPoint);
        }

        collectedPoints = targetPoint.collected
            ? [...collectedPoints, { id: targetPoint.id, lng: targetPoint.lng, lat: targetPoint.lat, fitConditions: targetPoint.fitConditions.join('、') }]
            : collectedPoints.filter(p => p.id !== targetId);

        localStorage.setItem('collectedPotentialPoints', JSON.stringify(collectedPoints));
        renderRecommendList();
        renderCollectList();

        if (selectedPoint && selectedPoint.id === targetId) {
            const btn = document.getElementById('detailCollectBtn');
            btn.classList.toggle('collected', targetPoint.collected);
            btn.innerHTML = targetPoint.collected ? '已收藏' : '收藏';
        }
    }

    // 保存到数据库提示
    function saveToDatabase(point) {
        const data = {
            id: point.id,
            longitude: point.lng,
            latitude: point.lat,
            conditions: point.fitConditions.join('、'),
            reason: point.reason,
            scene: currentScene
        };
        alert('需保存到数据库的真实地址信息：\n' + JSON.stringify(data, null, 2));
    }

    // 渲染收藏列表
    function renderCollectList() {
        const collectList = document.getElementById('collectList');
        if (collectedPoints.length === 0) {
            collectList.innerHTML = '<div style="text-align: center; color: #999; padding: 10px 0; font-size: 12px;">暂无收藏的选址</div>';
            return;
        }

        let html = '';
        collectedPoints.forEach((point, i) => {
            html += `
                <div class="collect-item">
                    <div class="collect-info">
                        <div class="collect-name">收藏选址${i + 1}</div>
                        <div class="collect-coord">${point.lng}, ${point.lat}</div>
                    </div>
                    <button class="cancel-collect-btn" onclick="cancelCollect('${point.id}')">
                        <i class="layui-icon">&#xe640;</i>
                    </button>
                </div>
            `;
        });
        collectList.innerHTML = html;
    }

    // 取消收藏
    function cancelCollect(pointId) {
        const potentialPoint = potentialPoints.find(p => p.id === pointId);
        if (potentialPoint) potentialPoint.collected = false;

        collectedPoints = collectedPoints.filter(p => p.id !== pointId);
        localStorage.setItem('collectedPotentialPoints', JSON.stringify(collectedPoints));
        renderCollectList();
        renderRecommendList();

        if (selectedPoint && selectedPoint.id === pointId) {
            const btn = document.getElementById('detailCollectBtn');
            btn.classList.remove('collected');
            btn.innerHTML = '收藏';
        }
    }

    // 获取选中的筛选条件
    function getSelectedFilters() {
        const filters = {};
        document.querySelectorAll('input[type="checkbox"]:checked').forEach(checkbox => {
            const groupId = checkbox.name;
            if (!filters[groupId]) filters[groupId] = [];
            filters[groupId].push(checkbox.value);
        });
        return filters;
    }

    // 清除标记
    function clearPotentialMarkers() {
        if (potentialMarkers.length) map.remove(potentialMarkers);
        potentialMarkers = [];
    }
    function clearSurroundMarkers() {
        if (surroundMarkers.length) map.remove(surroundMarkers);
        surroundMarkers = [];
    }
</script>
</body>
</html>